
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_Hans">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>使用 REMOTE_USER 进行身份验证 &#8212; Django 3.2.11.dev 文档</title>
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/language_data.js"></script>
    <link rel="index" title="索引" href="../genindex.html" />
    <link rel="search" title="搜索" href="../search.html" />
    <link rel="next" title="编写自定义 django-admin 命令" href="custom-management-commands.html" />
    <link rel="prev" title="操作指南" href="index.html" />



 
<script src="../templatebuiltins.js"></script>
<script>
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);</script>

  </head><body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../index.html">Django 3.2.11.dev 文档</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../index.html">Home</a>  |
        <a title="Table of contents" href="../contents.html">Table of contents</a>  |
        <a title="Global index" href="../genindex.html">Index</a>  |
        <a title="Module index" href="../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="index.html" title="操作指南">previous</a>
     |
    <a href="index.html" title="操作指南" accesskey="U">up</a>
   |
    <a href="custom-management-commands.html" title="编写自定义 &lt;code class=&#34;docutils literal notranslate&#34;&gt;&lt;span class=&#34;pre&#34;&gt;django-admin&lt;/span&gt;&lt;/code&gt; 命令">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="howto-auth-remote-user">
            
  <div class="section" id="s-authentication-using-remote-user">
<span id="authentication-using-remote-user"></span><h1>使用 <code class="docutils literal notranslate"><span class="pre">REMOTE_USER</span></code> 进行身份验证<a class="headerlink" href="#authentication-using-remote-user" title="永久链接至标题">¶</a></h1>
<p>本文档描述如何在 Django 应用中使用外部身份验证资源（在 web 服务器上设置 <code class="docutils literal notranslate"><span class="pre">REMOTE_USER</span></code> 环境变量的地方）。这种类型的身份验证方法一般用在使用了单点登录方案的内部网站上，比如 IIS 和 Windows 一体化验证或者 Apache 和 <a class="reference external" href="https://httpd.apache.org/docs/2.2/mod/mod_authnz_ldap.html">mod_authnz_ldap</a>, <a class="reference external" href="https://www.apereo.org/projects/cas">CAS</a>, <a class="reference external" href="http://weblogin.org">Cosign</a>, <a class="reference external" href="https://uit.stanford.edu/service/authentication">WebAuth</a>, <a class="reference external" href="https://sourceforge.net/projects/mod-auth-sspi">mod_auth_sspi</a> 等等。</p>
<p>当 Web 服务器负责鉴权时，通常会设置 <code class="docutils literal notranslate"><span class="pre">REMOTE_USER</span></code> 环境变量，这是为了在底层应用中使用。在 Django 中， <code class="docutils literal notranslate"><span class="pre">REMOTE_USER</span></code> 是作为 <a class="reference internal" href="../ref/request-response.html#django.http.HttpRequest.META" title="django.http.HttpRequest.META"><code class="xref py py-attr docutils literal notranslate"><span class="pre">request.META</span></code></a> 的参数来使用的。如果想在 Django 中使用 <code class="docutils literal notranslate"><span class="pre">REMOTE_USER</span></code>,  可以通过配置 <code class="docutils literal notranslate"><span class="pre">RemoteUserMiddleware</span></code> 中间件， <code class="docutils literal notranslate"><span class="pre">PersistentRemoteUserMiddleware</span></code> 中间件，或者继承在 <a class="reference internal" href="../topics/auth/index.html#module-django.contrib.auth" title="django.contrib.auth: Django's authentication framework."><code class="xref py py-mod docutils literal notranslate"><span class="pre">django.contrib.auth</span></code></a> 中的 <a class="reference internal" href="../ref/contrib/auth.html#django.contrib.auth.backends.RemoteUserBackend" title="django.contrib.auth.backends.RemoteUserBackend"><code class="xref py py-class docutils literal notranslate"><span class="pre">RemoteUserBackend</span></code></a> 来实现。</p>
<div class="section" id="s-configuration">
<span id="configuration"></span><h2>配置<a class="headerlink" href="#configuration" title="永久链接至标题">¶</a></h2>
<p>首先，你需要向配置文件的 <a class="reference internal" href="../ref/settings.html#std:setting-MIDDLEWARE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">MIDDLEWARE</span></code></a> 键中，在 <a class="reference internal" href="../ref/middleware.html#django.contrib.auth.middleware.AuthenticationMiddleware" title="django.contrib.auth.middleware.AuthenticationMiddleware"><code class="xref py py-class docutils literal notranslate"><span class="pre">django.contrib.auth.middleware.AuthenticationMiddleware</span></code></a> 的 <strong>后面</strong> 添加 <a class="reference internal" href="../ref/middleware.html#django.contrib.auth.middleware.RemoteUserMiddleware" title="django.contrib.auth.middleware.RemoteUserMiddleware"><code class="xref py py-class docutils literal notranslate"><span class="pre">django.contrib.auth.middleware.RemoteUserMiddleware</span></code></a></p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">MIDDLEWARE</span> <span class="o">=</span> <span class="p">[</span>
    <span class="s1">&#39;...&#39;</span><span class="p">,</span>
    <span class="s1">&#39;django.contrib.auth.middleware.AuthenticationMiddleware&#39;</span><span class="p">,</span>
    <span class="s1">&#39;django.contrib.auth.middleware.RemoteUserMiddleware&#39;</span><span class="p">,</span>
    <span class="s1">&#39;...&#39;</span><span class="p">,</span>
<span class="p">]</span>
</pre></div>
</div>
<p>然后，你需要将设置中的 <a class="reference internal" href="../ref/settings.html#std:setting-AUTHENTICATION_BACKENDS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">AUTHENTICATION_BACKENDS</span></code></a> setting:: 键值由 <a class="reference internal" href="../ref/contrib/auth.html#django.contrib.auth.backends.ModelBackend" title="django.contrib.auth.backends.ModelBackend"><code class="xref py py-class docutils literal notranslate"><span class="pre">ModelBackend</span></code></a> 替换为 <a class="reference internal" href="../ref/contrib/auth.html#django.contrib.auth.backends.RemoteUserBackend" title="django.contrib.auth.backends.RemoteUserBackend"><code class="xref py py-class docutils literal notranslate"><span class="pre">RemoteUserBackend</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">AUTHENTICATION_BACKENDS</span> <span class="o">=</span> <span class="p">[</span>
    <span class="s1">&#39;django.contrib.auth.backends.RemoteUserBackend&#39;</span><span class="p">,</span>
<span class="p">]</span>
</pre></div>
</div>
<p>通过此项设置， <code class="docutils literal notranslate"><span class="pre">RemoteUserMiddleware</span></code> 可以检测 <code class="docutils literal notranslate"><span class="pre">request.META['REMOTE_USER']</span></code> 中的用户名，而且可以认证和自动登录用户使用的 <a class="reference internal" href="../ref/contrib/auth.html#django.contrib.auth.backends.RemoteUserBackend" title="django.contrib.auth.backends.RemoteUserBackend"><code class="xref py py-class docutils literal notranslate"><span class="pre">RemoteUserBackend</span></code></a>。</p>
<p>要注意这项设置将导致无法使用默认的 <code class="docutils literal notranslate"><span class="pre">ModelBackend</span></code> 验证。也就是说如果 <code class="docutils literal notranslate"><span class="pre">REMOTE_USER</span></code> 的值没有指定则该用户将无法登录，即使通过 Django 的管理后台。要解决这些问题，把 <code class="docutils literal notranslate"><span class="pre">'django.contrib.auth.backends.ModelBackend'</span></code> 加入 <code class="docutils literal notranslate"><span class="pre">AUTHENTICATION_BACKENDS</span></code> 列表中，则当 <code class="docutils literal notranslate"><span class="pre">REMOTE_USER</span></code> 未指定时，就会回退使用 <code class="docutils literal notranslate"><span class="pre">ModelBackend</span></code>。</p>
<p>Django 的用户管理系统，比如 <code class="docutils literal notranslate"><span class="pre">contrib.admin</span></code> 中的视图函数及 <a class="reference internal" href="../ref/django-admin.html#django-admin-createsuperuser"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">createsuperuser</span></code></a> 的管理命令，都没有与远程用户集成。这些接口只工作在数据库中存储的用户上，无论 <code class="docutils literal notranslate"><span class="pre">AUTHENTICATION_BACKENDS</span></code> 为何值。</p>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p>因为 <code class="docutils literal notranslate"><span class="pre">RemoteUserBackend</span></code> 继承自 <code class="docutils literal notranslate"><span class="pre">ModelBackend</span></code>, 您仍将拥有在  <code class="docutils literal notranslate"><span class="pre">ModelBackend</span></code> 中实现的所有相同的权限检查。</p>
<p class="last">具有 <a class="reference internal" href="../ref/contrib/auth.html#django.contrib.auth.models.User.is_active" title="django.contrib.auth.models.User.is_active"><code class="xref py py-attr docutils literal notranslate"><span class="pre">is_active=False</span></code></a> 的用户将被禁止验证。你可以使用 <a class="reference internal" href="../ref/contrib/auth.html#django.contrib.auth.backends.AllowAllUsersRemoteUserBackend" title="django.contrib.auth.backends.AllowAllUsersRemoteUserBackend"><code class="xref py py-class docutils literal notranslate"><span class="pre">AllowAllUsersRemoteUserBackend</span></code></a> 来允许验证。</p>
</div>
<p>如果你的验证机制使用一个自定义的 HTTP header 而不是 <code class="docutils literal notranslate"><span class="pre">REMOTE_USER</span></code>，你可以构建一个 <code class="docutils literal notranslate"><span class="pre">RemoteUserMiddleWare</span></code> 的子类然后把 <code class="docutils literal notranslate"><span class="pre">header</span></code> 属性设成你希望的 <code class="docutils literal notranslate"><span class="pre">request.META</span></code> 键值。例如:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.contrib.auth.middleware</span> <span class="kn">import</span> <span class="n">RemoteUserMiddleware</span>

<span class="k">class</span> <span class="nc">CustomHeaderMiddleware</span><span class="p">(</span><span class="n">RemoteUserMiddleware</span><span class="p">):</span>
    <span class="n">header</span> <span class="o">=</span> <span class="s1">&#39;HTTP_AUTHUSER&#39;</span>
</pre></div>
</div>
<div class="admonition warning">
<p class="first admonition-title">警告</p>
<p>使用具有自定义HTTP头部的 <code class="docutils literal notranslate"><span class="pre">RemoteUserMiddleware</span></code> 子类时需要特别小心。你要确保你的前端服务器基于验证检查结果正确设置或去除了该头部，禁止任何终端用户提交一个仿冒的头部值。因为HTTP头部 <code class="docutils literal notranslate"><span class="pre">X-Auth-User</span></code> 与（比方说） <code class="docutils literal notranslate"><span class="pre">X-Auth_User</span></code> 都会标准化为 <code class="docutils literal notranslate"><span class="pre">request.META</span></code> 的 <code class="docutils literal notranslate"><span class="pre">HTTP_X_AUTH_USER</span></code> 键，你必须确保你的服务器不允许头部使用下划线来替代横杠。</p>
<p class="last">这个警告不适用于 <code class="docutils literal notranslate"><span class="pre">RemoteUserMiddlewar</span></code>，它的默认配置为 <code class="docutils literal notranslate"><span class="pre">header</span> <span class="pre">='REMOTE_USER'</span></code>, 因为在 <code class="docutils literal notranslate"><span class="pre">request.META</span></code> 中不存在以 <code class="docutils literal notranslate"><span class="pre">HTTP_</span></code> 开始的键可以只由WSGI服务器设置, 而不能直接来自HTTP请求头部.</p>
</div>
<p>如果你需要更多控制, 你可以通过继承 <a class="reference internal" href="../ref/contrib/auth.html#django.contrib.auth.backends.RemoteUserBackend" title="django.contrib.auth.backends.RemoteUserBackend"><code class="xref py py-class docutils literal notranslate"><span class="pre">RemoteUserBackend</span></code></a>  并且覆盖其一个或多个属性和方法来创建你自己的验证后端.</p>
</div>
<div class="section" id="s-using-remote-user-on-login-pages-only">
<span id="s-persistent-remote-user-middleware-howto"></span><span id="using-remote-user-on-login-pages-only"></span><span id="persistent-remote-user-middleware-howto"></span><h2>仅在登录界面使用 <code class="docutils literal notranslate"><span class="pre">REMOTE_USER</span></code><a class="headerlink" href="#using-remote-user-on-login-pages-only" title="永久链接至标题">¶</a></h2>
<p><code class="docutils literal notranslate"><span class="pre">RemoteUserMiddleware</span></code> 这个认证中间件 ，它假设HTTP请求的头部 <code class="docutils literal notranslate"><span class="pre">REMOTE_USER</span></code> 在所有认证请求中都存在。这个假设在当通过 <code class="docutils literal notranslate"><span class="pre">htpasswd</span></code> 或者相似的认证机制来做Basic HTTP的认证时才是可行的，但是使用Negotiate (GSSAPI/Kerberos) 或者其它资源密集型的认证方法时就说不过去了，前端HTTP server的认证通常用在仅仅一个或不太多的登录URLs，而且在认证成功后，应用还要自己去维护这个session。</p>
<p><a class="reference internal" href="../ref/middleware.html#django.contrib.auth.middleware.PersistentRemoteUserMiddleware" title="django.contrib.auth.middleware.PersistentRemoteUserMiddleware"><code class="xref py py-class docutils literal notranslate"><span class="pre">PersistentRemoteUserMiddleware</span></code></a> 就针对这个使用场景提供了支持。除非用户显式地退出登录，它将一直保留已认证的会话。这个中间件可以代替上文中的 <a class="reference internal" href="../ref/middleware.html#django.contrib.auth.middleware.RemoteUserMiddleware" title="django.contrib.auth.middleware.RemoteUserMiddleware"><code class="xref py py-class docutils literal notranslate"><span class="pre">RemoteUserMiddleware</span></code></a>。</p>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">使用 <code class="docutils literal notranslate"><span class="pre">REMOTE_USER</span></code> 进行身份验证</a><ul>
<li><a class="reference internal" href="#configuration">配置</a></li>
<li><a class="reference internal" href="#using-remote-user-on-login-pages-only">仅在登录界面使用 <code class="docutils literal notranslate"><span class="pre">REMOTE_USER</span></code></a></li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="index.html"
                        title="上一章">操作指南</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="custom-management-commands.html"
                        title="下一章">编写自定义 <code class="docutils literal notranslate"><span class="pre">django-admin</span></code> 命令</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/howto/auth-remote-user.txt"
            rel="nofollow">显示源代码</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>快速搜索</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="转向" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">12月 07, 2021</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="index.html" title="操作指南">previous</a>
     |
    <a href="index.html" title="操作指南" accesskey="U">up</a>
   |
    <a href="custom-management-commands.html" title="编写自定义 &lt;code class=&#34;docutils literal notranslate&#34;&gt;&lt;span class=&#34;pre&#34;&gt;django-admin&lt;/span&gt;&lt;/code&gt; 命令">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>